<template>
  <div class="home">
    <!-- 筛选 -->
    <div class="search_content">
      <van-nav-bar
        :title="$route.meta.title"
        left-text="返回"
        left-arrow
        @click-left="$router.go(-1)"
      />
      <van-search
        v-model="requestParams.codeNo"
        placeholder="请输入车架号或者车牌号"
        shape="round"
        @search="initData"
        @clear="clearSearch"
      />
      <div class="search_item">
        <van-dropdown-menu :close-on-click-outside="false">
          <van-dropdown-item title="保险公司" ref="insureRef">
            <div class="searchbox">
              <div class="title">推修保险公司</div>
              <div class="insureList">
                <div
                  class="insure_item"
                  :class="item.check ? 'active' : ''"
                  v-for="(item, index) in insureList"
                  :key="index"
                  @click="handleSelect(index, 'insureList')"
                >
                  {{ item.name }}
                </div>
              </div>
              <div class="insureBtn">
                <van-button
                  size="small"
                  type="warning"
                  class="resetBtn"
                  @click="handleReset(insureList)"
                >
                  重置
                </van-button>
                <van-button
                  size="small"
                  type="info"
                  class="confirmBtn"
                  @click="onConfirm('insureRef')"
                >
                  确认
                </van-button>
              </div>
            </div>
          </van-dropdown-item>

          <van-dropdown-item title="状态" ref="statusRef">
            <div class="searchbox">
              <div class="insureList">
                <div
                  class="insure_item"
                  :class="item.check ? 'active' : ''"
                  v-for="(item, index) in insureBillStatusList"
                  :key="index"
                  @click="handleSelect(index, 'insureBillStatusList')"
                >
                  {{ item.name }}
                </div>
              </div>
              <div class="insureBtn">
                <van-button
                  size="small"
                  type="warning"
                  class="resetBtn"
                  @click="handleReset(insureBillStatusList)"
                >
                  重置
                </van-button>
                <van-button
                  size="small"
                  type="info"
                  class="confirmBtn"
                  @click="onConfirm('statusRef')"
                >
                  确认
                </van-button>
              </div>
            </div>
          </van-dropdown-item>

          <van-dropdown-item title="筛选" ref="accidentRef">
            <div class="searchbox">
              <div class="title">事故类型</div>
              <div class="insureList">
                <div
                  class="insure_item"
                  :class="item.check ? 'active' : ''"
                  v-for="(item, index) in accidentTypeList"
                  :key="index"
                  @click="handleSelect(index, 'accidentTypeList')"
                >
                  {{ item.name }}
                </div>
              </div>
              <div class="title">是否推修</div>
              <div class="insureList">
                <div
                  class="insure_item"
                  :class="index == pushIndex ? 'active' : ''"
                  v-for="(item, index) in pushList"
                  :key="index"
                  @click="handlePushSelect(index, 'pushList')"
                >
                  {{ item.name }}
                </div>
              </div>
              <div class="title">出险日期</div>
              <div class="insureList">
                <van-field
                  v-model="requestParams.accidentStartDate"
                  label="开始时间"
                  :placeholder="'请选择'"
                  input-align="right"
                  readonly
                  right-icon="arrow"
                  @click="showPickerDate = true"
                />
                <van-field
                  v-model="requestParams.accidentEndDate"
                  label="结束时间"
                  :placeholder="'请选择'"
                  input-align="right"
                  readonly
                  right-icon="arrow"
                  @click="showPickerDate1 = true"
                />
              </div>
              <div class="insureBtn">
                <van-button
                  size="small"
                  type="warning"
                  class="resetBtn"
                  @click="handleAccidentReset(accidentTypeList)"
                >
                  重置
                </van-button>
                <van-button
                  size="small"
                  type="info"
                  class="confirmBtn"
                  @click="onConfirm('accidentRef')"
                >
                  确认
                </van-button>
              </div>
            </div>
          </van-dropdown-item>
        </van-dropdown-menu>

        <van-popup v-model="showPickerDate" position="bottom">
          <van-datetime-picker
            v-model="currentDate"
            type="date"
            @cancel="onCancelDate"
            @confirm="onConfirmDate"
            :formatter="formatter"
          />
        </van-popup>
        <van-popup v-model="showPickerDate1" position="bottom">
          <van-datetime-picker
            v-model="currentDate1"
            type="date"
            @cancel="onCancelDate1"
            @confirm="onConfirmDate1"
            :formatter="formatter"
          />
        </van-popup>
      </div>
    </div>

    <!-- 列表 -->
    <keep-alive>
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="loadData"
          v-if="recordList && recordList.length != 0"
        >
          <div class="orderList">
            <div
              class="orderItem"
              v-for="(item, index) in recordList"
              :key="index"
            >
              <div class="orderItem_header">
                <div class="orderItem_lt" @click="goDetail(item)">
                  <div class="carNo">{{ item.carNo }}</div>
                  <div class="carStatus">{{ item.billStatus }}</div>
                </div>
                <div class="orderItem_rt">
                  <i class="iconfont icon-tel"></i>
                  <div class="txt">
                    <a @click="handleTel(item.customerPhone)">联系车主</a>
                  </div>
                </div>
              </div>
              <div class="orderItem_content" @click="goDetail(item)">
                <div class="orderItem_data">
                  <i class="iconfont icon-fixCenter"></i>
                  <div class="txt">
                    {{ item.fixCenterName ? item.fixCenterName : "-" }}
                  </div>
                </div>
                <div class="orderItem_data">
                  <i class="iconfont icon-date"></i>
                  <div class="txt">{{ item.bizDate ? item.bizDate : "-" }}</div>
                </div>
                <div class="orderItem_data">
                  <i class="iconfont icon-address"></i>
                  <div class="txt">
                    {{
                      item.accidentAddress &&
                      JSON.stringify(item.accidentAddress) != "{}"
                        ? item.accidentAddress
                        : "-"
                    }}
                  </div>
                </div>
              </div>
              <div class="orderItem_file" @click="fileManage(item)">
                <i class="iconfont icon-file"></i>
                附件管理
              </div>
            </div>
          </div>
        </van-list>

        <van-empty class="noContent" description="暂无数据" v-else />
      </van-pull-refresh>
    </keep-alive>

    <div class="addBtn" v-if="isEdit">
      <div class="orderItem_filebox" @click="handleAdd">
        <i class="iconfont icon-add"></i>
        新建登记单
      </div>
    </div>

    <div class="loading" v-if="loading">
      <van-loading size="30px" class="loadbox" color="#fff" text-color="#fff">
        加载中...
      </van-loading>
      <div class="mask"></div>
    </div>
  </div>
</template>

<script>
import {
  Search,
  DropdownMenu,
  DropdownItem,
  Empty,
  Toast,
  Loading,
} from "vant";
import outAPi from "@/api/outAPi";
import commonApi from "@/api/commonApi";
import { getCookies, isPhone } from "@/utils/util.js";

export default {
  nama: "registerList",
  components: {
    Search,
    DropdownMenu,
    DropdownItem,
    Empty,
    Loading,
    Toast,
  },
  data() {
    return {
      insureList: [],

      pushList: [
        { name: "是", code: 1, check: false },
        { name: "否", code: 0, check: false },
      ],
      pushIndex: null,
      showPickerDate: false,
      showPickerDate1: false,
      currentDate: new Date(),
      currentDate1: new Date(),
      bgDate: "", // 查询时间
      endDate: "",
      recordList: [
        // {
        //   billId: "1", //单据ID
        //   carNo: "闽D66666", //车辆车牌号
        //   newCarNo: "闽D5555", //单据车牌号
        //   vinCode: "LIOIAUHHH11111", //车架号
        //   insComp: "平安", //保险公司
        //   customerName: "张三", //客户姓名
        //   customerPhone: "18778712311", //客户联系电话
        //   accidentAddress: "厦门", //出现地点
        //   billStatus: "提交", //单据状态
        //   bizDate: "2023-09-09", //业务日期
        //   accidentDate: "2023-09-08", //出险日期
        // },
      ],
      requestParams: {
        codeNo: "", //车架号或者车牌号，String，必填
        pageNo: 1, //当前页数，默认从1开始，每页显示十条，int，不能为空或者小于1
        accidentStartDate: "", //出现开始时间 yyyy-MM-dd
        accidentEndDate: "", //出现结束时间 yyyy-MM-dd
        insCompId: "", //保险公司ID值
        accidentType: "", //事故类型
        billStatus: "", //事故跟踪单状态
        isRepaired: "", //是否推修，1为是，2为否
        userId: getCookies("userId"), //用户ID，必填，String
      },
      // 分页参数
      loading: false,
      finished: false,
      refreshing: false,
      isLoadData: false,

      insuranceList: [], //保险类型
      insureTypeList: [], //保险分类
      insureBillStatusList: [], //保单单据状态
      accidentTypeList: [], //事故类型
      isEdit: isPhone(),
    };
  },
  // watch: {
  //   $route: {
  //     handler: function (val, oldVal) {
  //       console.log(val)
  //       if (val && val.query && localStorage.getItem('switch')) {
  //         this.initData()
  //       }
  //     },
  //     deep: true,
  //     immediate: false,
  //   },
  // },

  mounted() {
    this.getInsureType();
    this.getInsurance();
    this.getInsureBillStatus();
    this.getInsComList();
    this.getAccidentType();
    this.initData();
  },

  methods: {
    // 初始化列表
    initData() {
      this.requestParams.pageNo = 1;
      this.loadData();
    },
    // 获取列表
    loadData() {
      if (this.isLoadData) return;
      this.isLoadData = true;
      this.loading = true;
      this.finished = false;
      // console.log(this.isLoadData);
      outAPi
        .queyCarAccidentTrackingBill({ ...this.requestParams })
        .then((res) => {
          if (res) {
            if (this.requestParams.pageNo == 1) {
              this.recordList = res.data || [];
            } else {
              this.recordList = this.recordList.concat(res.data || []);
            }
            this.requestParams.pageNo += 1;

            if (res.data.length < 10) {
              this.finished = true;
              this.isLoadData = true;
            }
            this.isLoadData = false;
            this.loading = false;
          }
        })
        .catch((res) => {
          this.isLoadData = false;
          this.loading = false;
        });
    },
    // 下拉刷新
    onRefresh() {
      // 清空列表数据
      this.recordList = [];
      this.finished = false;
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true;
      this.refreshing = false;
      this.initData();
    },

    // 获取保险分类
    getInsureType() {
      commonApi
        .getEnums({ key: "insureType", userId: this.requestParams.userId })
        .then((res) => {
          if (res.data) {
            this.insureTypeList = res.data;
          }
        });
    },
    // 获取保险类型
    getInsurance() {
      commonApi
        .getEnums({ key: "insurance", userId: this.requestParams.userId })
        .then((res) => {
          if (res.data) {
            this.insuranceList = res.data;
          }
        });
    },
    // 获取保单单据状态
    getInsureBillStatus() {
      commonApi
        .getEnums({
          key: "carAccidentBillStatus",
          userId: this.requestParams.userId,
        })
        .then((res) => {
          if (res.data) {
            this.insureBillStatusList = this.formatCheckData(res.data);
          }
        });
    },
    // 获取事故类型
    getAccidentType() {
      commonApi
        .getEnums({
          key: "accidentType",
          userId: this.requestParams.userId,
        })
        .then((res) => {
          if (res.data) {
            this.accidentTypeList = this.formatCheckData(res.data);
          }
        });
    },
    // 保险公司
    getInsComList() {
      commonApi
        .getBaseCode({
          key: "保险公司",
          userId: this.requestParams.userId,
        })
        .then((res) => {
          if (res.data) {
            this.insureList = this.formatCheckData(res.data);
          }
        });
    },
    // 格式化多选数据
    formatCheckData(data) {
      data.forEach((item) => {
        item.check = false;
      });
      return data;
    },

    handleSelect(index, listKey) {
      this[listKey][index].check = !this[listKey][index].check;
    },
    // 是否推修
    handlePushSelect(index) {
      this.pushIndex = index;
    },
    handleReset(data) {
      data.forEach((item) => {
        item.check = false;
      });
    },
    // 筛选重置
    handleAccidentReset(data) {
      data.forEach((item) => {
        item.check = false;
      });
      this.pushIndex = null;
      this.requestParams.accidentStartDate = null;
      this.requestParams.accidentEndDate = null;
    },
    onConfirm(ref) {
      let arr = [];
      if (ref == "insureRef") {
        this.insureList.forEach((item, index) => {
          if (item.check) {
            arr.push(item.billId);
          }
        });
        this.requestParams.insCompId = arr.join(";");
      }
      if (ref == "statusRef") {
        this.insureBillStatusList.forEach((item, index) => {
          if (item.check) {
            arr.push(item.value);
          }
        });
        this.requestParams.billStatus = arr.join(";");
      }
      if (ref == "accidentRef") {
        this.accidentTypeList.forEach((item, index) => {
          if (item.check) {
            arr.push(item.value);
          }
        });
        this.requestParams.isRepaired = this.pushIndex
          ? this.pushList[this.pushIndex].code
          : "";
        this.requestParams.accidentType = arr.join(";");
      }
      this.initData();
      this.$refs[ref].toggle();
    },
    onConfirmDate() {
      this.requestParams.accidentStartDate = `${this.value1}-${this.value2}-${this.value3}`; // 字符串拼接 结果入2020-07-03
      this.onCancelDate();
    },
    onConfirmDate1() {
      this.requestParams.accidentEndDate = `${this.value1}-${this.value2}-${this.value3}`; // 字符串拼接 结果入2020-07-03
      this.onCancelDate1();
    },
    onCancelDate() {
      this.showPickerDate = false;
    },
    onCancelDate1() {
      this.showPickerDate1 = false;
    },
    // 日期组件自定义格式
    formatter(type, value) {
      if (type === "year") {
        this.value1 = value; // 可以拿到当前点击的数值
        return `${value}年`;
      } else if (type === "month") {
        this.value2 = value;
        return `${value}月`;
      }
      this.value3 = value;
      return `${value}日`;
    },

    getFieldName(list, key, val) {
      if (list && list.length > 0) {
        let obj = list.filter((item) => {
          return item[key] == val;
        });
        if (obj.length > 0) {
          return obj[0].name;
        }
      }
      return null;
    },
    fileManage(data) {
      this.$router.push({
        path: "/fileMange",
        query: { billId: data.billId },
      });
    },
    goDetail(data) {
      this.$router.push({
        path: "/registerDetail",
        query: { billId: data.billId },
      });
    },
    handleAdd() {
      this.$router.push({ path: "/registerEdit" });
    },
    clearSearch() {
      this.requestParams.codeNo = "";
      this.initData();
    },
    handleTel(tel) {
      if (isPhone()) {
        window.location.href = `tel:${tel}`;
      } else {
        Toast("请在手机端使用此功能");
      }
    },
    onClickLeft() {
      this.$router.go(-1);
    },
  },
};
</script>

<style lang="less" scoped="">
.home {
  background: #f3f3f3;
}

.search_content {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 2;
}
.searchbox {
  padding: 0.3rem;
  .title {
    font-size: 0.3rem;
    font-weight: bold;
    color: #333;
    margin-bottom: 0.4rem;
    padding-top: 0.2rem;
  }
  .insureList {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-wrap: wrap;
    .insure_item {
      text-align: center;
      padding: 0.15rem 0rem;
      width: 30%;
      box-sizing: border-box;
      font-size: 0.28rem;
      border-radius: 3px;
      color: #666;
      margin-bottom: 0.2rem;
      margin-right: 5%;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      box-shadow: 0px 0px 2px 0px rgba(0, 0, 0, 0.5);
      &:nth-child(3n) {
        margin-right: 0;
      }
      &.active {
        box-shadow: 0px 0px 3px 0px #f65e07;
        color: #f65e07;
      }
    }
  }
  .insureBtn {
    display: flex;
    justify-content: flex-end;

    margin-top: 0.4rem;
    .resetBtn {
      padding: 0 0.4rem;
      margin-right: 0.2rem;
    }
    .confirmBtn {
      padding: 0 0.4rem;
    }
  }
}

.orderList {
  padding-top: 3rem;
  margin: 0.3rem;
  overflow: hidden;
  .orderItem {
    padding: 0.3rem;
    background: #fff;
    border-radius: 10px;
    margin-bottom: 0.3rem;
    .orderItem_header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 0.3rem;
      padding-bottom: 0.2rem;
      border-bottom: 1px solid #f6f6f6;
      .orderItem_lt {
        // display: flex;
        align-items: center;
        align-self: center;
        // justify-content: flex-start;

        .carNo {
          font-size: 0.3rem;
          color: #333;
          margin-right: 0.2rem;
          font-weight: bold;
          margin-bottom: 10px;
        }
        .carStatus {
          background: #ffb65e;
          color: #fff;
          border-radius: 50px;
          padding: 0.1rem 0.2rem;
          font-size: 0.24rem;
          text-align: center;
        }
      }
      .orderItem_rt {
        display: flex;
        align-items: center;
        align-self: center;
        justify-content: flex-start;
        .txt {
          font-size: 0.28rem;
          color: #161616;
        }
        .icon-tel {
          color: #fff;
          background: #35bc04;
          font-size: 0.32rem;
          padding: 0.1rem;
          border-radius: 50%;
          margin-right: 0.1rem;
        }
      }
    }
    .orderItem_content {
      .orderItem_data {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        width: 100%;
        margin-bottom: 0.2rem;
        font-size: 0.28rem;
        color: #333;
        .iconfont {
          font-size: 0.4rem;
          margin-right: 0.2rem;
          color: #999;
        }
      }
    }
    .orderItem_file {
      background: #ebebeb;
      color: #333;
      border-radius: 5px;
      padding: 0.2rem 0;
      text-align: center;
      width: 100%;
      font-size: 0.28rem;
      display: flex;
      align-items: center;
      justify-content: center;

      .icon-file {
        font-size: 0.34rem;
        color: #333;
        margin-right: 0.1rem;
      }
    }
  }
}
.addBtn {
  position: fixed;
  bottom: 0.8rem;
  width: 100%;
  z-index: 1;
  .orderItem_filebox {
    width: 2.8rem;
    margin: auto;
    text-align: center;
    font-size: 0.28rem;
    background: #409eff;
    color: #fff;
    padding: 0.25rem 0rem;
    border-radius: 50px;
  }
}
.noContent {
  margin-top: 2rem;
}
</style>
